package org.orcas.kocl.compiler.util;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

public class TemplateUtil {
	
	public static String process(String opName, Map<String, String> map)  {
		
		try {
			Template template = _getTemplate(opName);
			
			StringWriter writer = new StringWriter();
			template.process(map, writer);
			writer.flush();
			
			return writer.toString();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return StringPool.BLANK;
	}
	
	
	private static Configuration _getConfiguration(){
		if (_cfg == null){
			_cfg = new Configuration();
			_cfg.setObjectWrapper(new DefaultObjectWrapper());
			_cfg.setTemplateLoader(
					new ClassTemplateLoader(TemplateUtil.class, "/"));
		}
		return _cfg;
	}
	
	private static String _getFilePath(String opName){
		return "templates/" + opName + ".ftl"; 
	}
	
	private static Template _getTemplate(String opName) throws IOException{
		String name = _getFilePath(opName);
		return _getConfiguration().getTemplate(name);
	}
	
	private static Configuration _cfg;
}
